#coding:utf-8

from lib.models import Course
from lib.models import Grade
from lib.models import Settings
from google.appengine.ext import db
from lib import students_parser
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.runtime import DeadlineExceededError
from datetime import datetime
from lib import update



def run_update(num):

    query = db.GqlQuery("SELECT * FROM Course WHERE has_results=False ORDER BY updated ASC")
    courses = query.fetch(num)

    items_updated = []
 
    for course in courses:

        update.update(course)
        items_updated.append(course.name)

    return items_updated


def is_time_to_update():
    
    now = datetime.now()
    today8  = now.replace(hour=5, minute=0, second=0)
    today14 = now.replace(hour=11, minute=0, second=0)
    today18 = now.replace(hour=15, minute=0, second=0)
    today19 = now.replace(hour=16, minute=0, second=0)

    times = [{"start":today8, "end":today14},{"start":today18, "end":today19}]
    now = datetime.now()
    for time_period in times:
        if now>time_period['start'] and now < time_period['end']:
            return True
    return False



class MainPage(webapp.RequestHandler):
    def get(self):

        force = self.request.get('force')
        number_of_courses = int(self.request.get('num', default_value="2"))

        if is_time_to_update() or force=="true":

            names = run_update(number_of_courses)

            for name in names:
                self.response.out.write("OK " + name + "<br />")

        else:
            self.response.out.write("not a good time")

application = webapp.WSGIApplication(
                                     [('/updatenext', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
